package com.mark.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.achievement.dao.ScoreRepository;
import com.achievement.entity.Course;
import com.achievement.entity.Score;
import com.alibaba.fastjson.JSONObject;
import com.common.util.TablePage;
import com.exam.dao.ExamRepository;
import com.exam.entity.Exam;
import com.mark.dao.StuAnswerRepository;
import com.mark.dao.StuOptionsRepository;
import com.mark.entity.StuAnswer;
import com.mark.entity.StuOptions;
import com.paper.entity.Subtopics;
import com.question.dao.OptionsRepository;
import com.question.entity.Options;
import com.user.entity.Student;

@Service
@Transactional
public class StuAnswerService implements IStuAnswerService{
	@Autowired
	private StuAnswerRepository stuAnswerDao;
	@Autowired
	private StuOptionsRepository stuOptionsDao;
	@Autowired
	private OptionsRepository optionsDao;
	@Autowired
	private ExamRepository examDao;
	@Autowired
	private ScoreRepository scoreDao;


	public TablePage<StuAnswer> findPage(Specification<StuAnswer> spec, Pageable pageable) {
		// TODO Auto-generated method stub
		Page<StuAnswer> page = stuAnswerDao.findAll(spec, pageable);
		return TablePage.getTablePage(page);
	}

	@Override
	public StuAnswer findOne(Long id) {
		// TODO Auto-generated method stub
		return stuAnswerDao.findOne(id);
	}

	@Override
	public StuAnswer findByStuAndExam(Long stuId, Long eId) {
		// TODO Auto-generated method stub
		return stuAnswerDao.findByStuAndExam(stuId, eId);
	}

	@Override
	public void selectAnswer(StuOptions stuOptions) {
		// TODO Auto-generated method stub
		StuOptions old = stuOptionsDao.findOne(stuOptions.getId());
		
		List<Long> ids = new ArrayList<Long>();
		for(Integer i:old.getOptions().keySet()) {
			ids.add(old.getOptions().get(i).getId());
		}
		
		stuOptionsDao.save(stuOptions);
		
		for(Long l:ids) {
			System.out.println("删除:"+l);
			optionsDao.delete(l);
		}
		
	}

	@Override
	public void commitAnswer(Long stuAnswerId) {
		// TODO Auto-generated method stub
		StuAnswer stuAnswer = stuAnswerDao.findOne(stuAnswerId);
		stuAnswer.setCompleted(true);
		stuAnswerDao.save(stuAnswer);
	}

	@Override
	public boolean isTimeLess(Long stuAnswerId) {
		// TODO Auto-generated method stub
		StuAnswer stuAnswer = stuAnswerDao.findOne(stuAnswerId);
		Exam exam = stuAnswer.getExam();
		
		Date now = new Date();
		
		Long lessTime = exam.getDate().getTime()+exam.getPaper().getTime()*60*1000-now.getTime();
		
		if(lessTime/(60*1000)>30)
			return true;
		return false;
	}

	@Override
	public Integer findTaskNum(Long teacher_id) {
		// TODO Auto-generated method stub
		List<Exam> exams = examDao.findByTeacherId(teacher_id);
		Integer result = 0;
		
		for(Exam e:exams) {
			Integer num = stuAnswerDao.getTaskCountByExamId(e.getId());
			result += num;
		}
		
		return result;
	}

	@Override
	public List<Exam> findTask(Long teacher_id) {
		// TODO Auto-generated method stub
		List<Exam> exams = examDao.findByTeacherId(teacher_id);
		return exams;
	}

	@Override
	public List<StuAnswer> findUnMarkList(Long exam_id) {
		// TODO Auto-generated method stub
		
		return stuAnswerDao.findUnMarkedList(exam_id);
	}

	@Override
	public String startMarked(Long exam_id) {
		// TODO Auto-generated method stub
		
		List<StuAnswer> stuAnswers = stuAnswerDao.findUnMarkedList(exam_id);
		boolean flag = false;
		if(stuAnswers.size()<=0)
			return "{\"success\":false,\"msg\":\"阅卷完毕!\"}";
		for(StuAnswer s:stuAnswers) {
			int num = 0;
			for(StuOptions stuOptions:s.getStuOptions()) {
				if(!stuOptions.isMarked()&&null!=stuOptions.getSubtopics().getSingle()) {
					System.out.println("getOptions的option"+stuOptions.getOptions().get(1));
					if(stuOptions.getOptions().size()<=0||stuOptions.getOptions().get(1).getContent().equals("")) {
						stuOptions.setScore(0);
					}else {
						Options option = stuOptions.getOptions().get(1);
						Long stu_id = Long.parseLong(option.getContent());
						if(stu_id==stuOptions.getSubtopics().getSingle().getAnswer().getId()) {
							//选项正确
							stuOptions.setScore(stuOptions.getSubtopics().getScore());
						}else {
							stuOptions.setScore(0);
						}
					}
					System.out.println("自动批阅单选题:"+stuOptions.getScore()+"分");
					stuOptions.setMarked(true);
					stuOptionsDao.save(stuOptions);
					num ++;
				}else if(!stuOptions.isMarked()&&null!=stuOptions.getSubtopics().getMultiple()) {
					if(stuOptions.getOptions().size()<=0) {
						stuOptions.setScore(0);
					}else {
						List<Long> stu_ids = new ArrayList<Long>();
						for(Integer i:stuOptions.getOptions().keySet()) {
							stu_ids.add(Long.parseLong(stuOptions.getOptions().get(i).getContent()));
						}
						int stu_num = 0;
						for(Options o:stuOptions.getSubtopics().getMultiple().getAnswers()) {
							
							for(Long l:stu_ids) {
								if(l==o.getId())
									stu_num++;
							}
						}
						if(stu_num==stuOptions.getSubtopics().getMultiple().getAnswers().size()) {
							//选项正确
							stuOptions.setScore(stuOptions.getSubtopics().getScore());
						}else {
							stuOptions.setScore(0);
						}
					}
					System.out.println("自动批阅多选题:"+stuOptions.getScore()+"分");
					stuOptions.setMarked(true);
					stuOptionsDao.save(stuOptions);
					num ++;
				}else if(!stuOptions.isMarked()&&null!=stuOptions.getSubtopics().getJudgment()) {
					
					if(stuOptions.getOptions().size()<=0) {
						stuOptions.setScore(0);
					}else{
						Long stu_id = Long.parseLong(stuOptions.getOptions().get(1).getContent());
						if(stu_id==stuOptions.getSubtopics().getJudgment().getAnswer().getId()) {
							//选项正确
							stuOptions.setScore(stuOptions.getSubtopics().getScore());
						}else {
							stuOptions.setScore(0);
						}
					}
					System.out.println("自动批阅判断题:"+stuOptions.getScore()+"分");
					stuOptions.setMarked(true);
					stuOptionsDao.save(stuOptions);
					num ++;
				}else {
					
				}
			}
			if(num==s.getStuOptions().size()) {
				s.setMarked(true);
				stuAnswerDao.save(s);
				flag = true;
			}
		}
		//判断是否全部题目阅卷完毕
		if(flag) {
			Exam exam = examDao.findOne(exam_id);
			exam.setMarked(true);
			examDao.save(exam);
			for(StuAnswer s:stuAnswers) {
				generateScore(s.getId());
				stuAnswerDao.save(s);
			}
			//不跳转、阅卷已完成
			return "{\"success\":false,\"msg\":\"阅卷完毕!\"}";
		}else {
			return "{\"success\":true,\"msg\":\"进入阅卷页面!\"}";
		}
	}



	@Override
	public boolean isAllStuMarked(Long exam_id) {
		if(stuAnswerDao.getTaskCountByExamId(exam_id)<=0) {
			return true;
		}
		return false;
	}

	@Override
	public void markStuAnswer(Long stuOptionsId, float score) {
		// TODO Auto-generated method stub
		StuOptions stuOptions = stuOptionsDao.findOne(stuOptionsId);
		stuOptions.setScore(score);
		stuOptionsDao.save(stuOptions);
	}

	@Override
	public void generateScore(Long stuAnswerId) {
		// TODO Auto-generated method stub
		/*private Long id;
		private float score;
		private Exam exam;
		private StuAnswer stuAnswer;
		private Student student;*/
		StuAnswer stuAnswer = stuAnswerDao.findOne(stuAnswerId);
		Score score = new Score();
		
		float total_score = 0;
		for(StuOptions s:stuAnswer.getStuOptions()) {
			System.out.println("stuoptions得分"+s.getScore());
			total_score += s.getScore();
		}
		Exam exam = stuAnswer.getExam();
		Student student = stuAnswer.getStudent();
		Course course = exam.getCourse();
		
		score.setScore(total_score);
		score.setExam(exam);
		score.setStuAnswer(stuAnswer);
		score.setStudent(student);
		score.setCourse(course);
		System.out.println("生成"+student.getName()+"的成绩"+total_score);
		scoreDao.save(score);
		
	}

	@Override
	public String markOne(StuAnswer stuAnswer) {
		// TODO Auto-generated method stub
		for(StuOptions s:stuAnswer.getStuOptions()) {
			StuOptions stuOptions = stuOptionsDao.findOne(s.getId());
			stuOptions.setScore(s.getScore());
			stuOptions.setMarked(true);
			stuOptionsDao.save(stuOptions);
		}
		StuAnswer old = stuAnswerDao.findOne(stuAnswer.getId());
		old.setMarked(true);
		stuAnswerDao.save(old);
		generateScore(old.getId());
		
		List<StuAnswer> list = stuAnswerDao.findUnMarkedList(old.getExam().getId());
		if(list.size()<=0) {
			
			//全部阅卷完毕
			//设置exam为marked
			Exam exam = old.getExam();
			exam.setMarked(true);
			System.out.println("所有阅卷完成，设exam为marked");
			examDao.save(exam);
			
			return "{\"num\":0}";
		}else {
			JSONObject json = (JSONObject) JSONObject.toJSON(list.get(0));
			String jsonStr = json.toString();
			return "{\"num\":"+list.size()+",\"stuAnswer\":"+jsonStr+"}";
		}

	}

	@Override
	public String getTask(Long exam_id) {
		// TODO Auto-generated method stub
		
		List<StuAnswer> list = stuAnswerDao.findUnMarkedList(exam_id);
		if(list.size()<=0) {
			
			//全部阅卷完毕
			//设置exam为marked
			Exam exam = examDao.findOne(exam_id);
			exam.setMarked(true);
			examDao.save(exam);
			
			
			
			return "{\"num\":0}";
		}else {
			JSONObject json = (JSONObject) JSONObject.toJSON(list.get(0));
			String jsonStr = json.toString();
			return "{\"num\":"+list.size()+",\"stuAnswer\":"+jsonStr+"}";
		}
	}
	

}
